﻿using System;
using Leo.Blog.DAL.SysModule;
using Leo.Blog.Model;
using Leo.Blog.ViewModel.SysModule;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Leo.Blog.Common.Encrypt;
using LinqToExcel;

namespace Leo.Blog.BLL.SysModule
{
    public class Sys_Account_B
    {
        private Sys_Account_D _sysAccountD = new Sys_Account_D();
        public UserAccountVM Login(string userId, string password)
        {
            Sys_Account account = _sysAccountD.FindSingle(m => m.Account == userId && m.Password == password&&m.IsEnable==1);
            if (account == null)
            {
                return null;
            }
            //int orgId = 0;//默认组织ID为0，设置时需要默认设置orgId=0
            //账号密码正确，查找各种权限组织
            UserAccountVM accountVM = new UserAccountVM();
            accountVM.UserId = account.Id;
            accountVM.Account = account.Account;
            accountVM.UserName = account.Name;
            Sys_OrgUser_D _orgUserD = new Sys_OrgUser_D();
            List<int> orgs = _orgUserD.LoadList(m=>m.AccountId==account.Id).Select(m=>m.OrgId.Value).ToList();
            //根据用户和组织选出角色ID
            Sys_UserRole_D _sysUserRoleD = new Sys_UserRole_D();
            Sys_OrgRole_D _sysOrgRoleD = new Sys_OrgRole_D();
            var userRoles = _sysUserRoleD.LoadList(m =>m.UserId==account.Id).Select(m=>m.RoleId);
            var orgRoles = _sysOrgRoleD.LoadList(m =>orgs.Contains(m.OrgId.Value)).Select(m => m.RoleId);
            var roles = userRoles.Concat(orgRoles).Distinct();//用户拥有的角色ID
            Sys_Roles_D _sysRolesD = new Sys_Roles_D();
            List<int> rolesIsenable = _sysRolesD.LoadList(m => roles.Contains(m.RoleId) && m.IsEnable == 1)
                                .Select(m => m.RoleId).ToList();//有效的角色ID

            //根据角色选择分配到的模块ID
            Sys_RoleModule_D _sysRoleModuleD = new Sys_RoleModule_D();
            var roleModules = _sysRoleModuleD.LoadList(m => rolesIsenable.Contains(m.RoleId.Value)).Select(m => m.ModuleId);
            //根据账号设置的模块
            Sys_UserModule_D _sysUserModuleD = new Sys_UserModule_D();
            var userModules = _sysUserModuleD.LoadList(m => m.UserId == account.Id).Select(m => m.ModuleId);

            List<int?> modules = roleModules.Concat(userModules).Distinct().ToList();

            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            List<Sys_Modules> listModules = _sysModulesD.LoadList(u => modules.Contains(u.ModuleId)&&u.IsEnable==1).ToList();
            var list = (from lm in listModules
                        select new UserModule
                        {
                            ModuleId = lm.ModuleId,
                            ModuleName = lm.ModuleName,
                            ModuleDesc = lm.ModuleDesc,
                            WebUrl = lm.WebUrl,
                            UrlPara = lm.UrlPara,
                            ParentModuleId = lm.ParentModuleId,
                            ParentName = lm.ParentName,
                            ModulePath=lm.ModulePath,
                            SortNo = lm.SortNo,
                            IsAutoExpend = lm.IsAutoExpend,
                            IconName = lm.IconName
                        }).OrderBy(m=>m.SortNo).ToList();
            accountVM.Modules = list;
            accountVM.Roles = rolesIsenable;
            accountVM.Orgs = orgs.Count > 0 ? orgs : new List<int> { 0 };
            return accountVM;

        }
        /// <summary>
        /// admin直接登录
        /// </summary>
        /// <returns></returns>
        public UserAccountVM Login()
        {
            Sys_Modules_D _sysModulesD = new Sys_Modules_D();
            UserAccountVM accountVM = new UserAccountVM();
            accountVM.UserId = 0;
            accountVM.Account = "admin";
            accountVM.UserName = "admin";
            List<Sys_Modules> listModules = _sysModulesD.LoadList().ToList();
            var list = (from lm in listModules
                        select new UserModule
                        {
                            ModuleId = lm.ModuleId,
                            ModuleName = lm.ModuleName,
                            ModuleDesc = lm.ModuleDesc,
                            WebUrl = lm.WebUrl,
                            UrlPara=lm.UrlPara,
                            ParentModuleId = lm.ParentModuleId,
                            ParentName = lm.ParentName,
                            ModulePath = lm.ModulePath,
                            SortNo = lm.SortNo,
                            IsAutoExpend = lm.IsAutoExpend,
                            IconName = lm.IconName
                        }).OrderBy(m => m.SortNo).ToList();
            accountVM.Modules = list;
            Sys_Roles_D _sysRolesD = new Sys_Roles_D();
            List<int> rolesIsenable = _sysRolesD.LoadList().Select(m => m.RoleId).ToList();
            accountVM.Roles = rolesIsenable;
            accountVM.Orgs = new List<int> { 0 };//默认组织ID为0
            return accountVM;
        }

        public static List<SysUserVM> GetUserAccounts(SysUserVM vm, int orgId, int page, int rows, out int totalCount)
        {
            Sys_Account acc = new Sys_Account
            {
                Account = vm.Account,
                Name = vm.Name,
                TelePhone = vm.TelePhone,
                IsEnable = vm.IsEnable
            };
            List<Sys_Account> listAccount = Sys_Account_D.GetAccounts(acc, orgId, page, rows, out totalCount);

            var list = (from la in listAccount
                select new SysUserVM
                {
                    Id=la.Id,
                    Account=la.Account,
                    Name=la.Name,
                    NickName=la.NickName,
                    Password=la.Password,
                    Email=la.Email,
                    TelePhone=la.TelePhone,
                    QQ=la.QQ,
                    IsEnable=la.IsEnable,
                    CreateBy=la.CreateBy,
                    CreateDT=la.CreateDT 
                }).ToList();
            return list;
        }



        public static bool CheckImportData(string fileName, List<SysUserVM> users, ref StringBuilder errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {
                errors.Append("导入的数据文件不存在<br/>");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<SysUserVM>(x => x.Account, "Account");//列名对应可以是中文
            excelFile.AddMapping<SysUserVM>(x => x.Password, "Password");
            excelFile.AddMapping<SysUserVM>(x => x.Name, "Name");
            excelFile.AddMapping<SysUserVM>(x => x.NickName, "NickName");
            excelFile.AddMapping<SysUserVM>(x => x.Email, "Email");
            excelFile.AddMapping<SysUserVM>(x => x.TelePhone, "TelePhone");
            excelFile.AddMapping<SysUserVM>(x => x.QQ, "QQ");
            excelFile.AddMapping<SysUserVM>(x => x.IsEnable, "IsEnable");
            excelFile.AddMapping<SysUserVM>(x => x.CreateBy, "CreateBy");
            //SheetName
            var excelContent = excelFile.Worksheet<SysUserVM>(0);

            int rowIndex = 1;

            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var person = new SysUserVM();
                person.Account = row.Account;
                person.Password = EncryptTools.GetMD5(row.Password);
                person.Name = row.Name;
                person.NickName = row.NickName;
                person.Email = row.Email;
                person.TelePhone = row.TelePhone;
                person.QQ = row.QQ;
                person.IsEnable = row.IsEnable;
                person.CreateBy = row.CreateBy;

                if (string.IsNullOrWhiteSpace(row.Account))
                {
                    errorMessage.Append("Account - 不能为空. ");
                }

                if (string.IsNullOrWhiteSpace(row.Password))
                {
                    errorMessage.Append("Password - 不能为空. ");
                }

                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Append(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                users.Add(person);
                rowIndex += 1;
            }
            if (errors.Length > 0)
            {
                return false;
            }
            return true;
        }

        public static bool SaveImportData(List<SysUserVM> users)
        {
            Sys_Account_D sysAccountD = new Sys_Account_D();
            List<Sys_Account> accounts = users.Select(m => new Sys_Account
            {
                Account = m.Account,
                Password=m.Password,
                Name=m.Name,
                NickName=m.NickName,
                Email = m.Email,
                TelePhone = m.TelePhone,
                QQ = m.QQ,
                IsEnable = m.IsEnable,
                CreateBy=m.CreateBy,
                CreateDT=DateTime.Now
            }).ToList();
            bool res= sysAccountD.AddList(accounts);
            return res;
        }

        public static List<SysUserVM> GetExportUserAccounts(SysUserVM vm, int orgId)
        {
            Sys_Account acc = new Sys_Account
            {
                Account = vm.Account,
                Name = vm.Name,
                TelePhone = vm.TelePhone,
                IsEnable = vm.IsEnable
            };
            List<Sys_Account> listAccount = Sys_Account_D.GetExportAccounts(acc, orgId);

            var list = (from la in listAccount
                        select new SysUserVM
                        {
                            Id = la.Id,
                            Account = la.Account,
                            Name = la.Name,
                            NickName = la.NickName,
                            Password = la.Password,
                            Email = la.Email,
                            TelePhone = la.TelePhone,
                            QQ = la.QQ,
                            IsEnable = la.IsEnable,
                            CreateBy = la.CreateBy,
                            CreateDT = la.CreateDT
                        }).ToList();
            return list;
        }
    }
}
